package com.zc.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zc.blog.model.Comment;
import com.zc.blog.model.Visitor;
import com.zc.blog.service.ICommentService;
import com.zc.blog.service.IVisitorService;
import com.zc.blog.service.QiNiuService;
import com.zc.blog.util.EmailUtil;
import com.zc.blog.util.MD5Util;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;


@Controller
@RequestMapping("/visitor")
public class VisitorController {

    @Autowired
    private IVisitorService visitorService;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private QiNiuService qiNiuService;

    /**
     * 修改头像
     * @param session
     * @throws NoSuchAlgorithmException
     */
    @PostMapping("/uploadAvatar")
    public String uploadAvatar(@RequestParam("avatar") MultipartFile file,  @RequestParam("nickname") String nickname,Model model,HttpSession session) {
        if (session.getAttribute("getVisitor") == null) {
            model.addAttribute("message","请登录");
            return "blog/visitorUploadAvatar";
        }
        Visitor getVisitor = (Visitor) session.getAttribute("getVisitor");
        if (file.isEmpty()) {
            model.addAttribute("message", "文件不能为空");
            return "blog/visitorUploadAvatar";
        }
        if (nickname!=null && !nickname.equals("")) {
            getVisitor.setVisitorName(nickname);
        }

        try {
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); // 获取文件后缀
            String newFileName = UUID.randomUUID() + fileExtension; // 生成唯一文件名

            // 定义存储路径（本地）
            String fileUrl = qiNiuService.uploadToQiNiu(file.getBytes(), newFileName);//上传七牛云

            // 更新数据库中的头像路径
            getVisitor.setVisitorAvatar(newFileName);
            visitorService.updateById(getVisitor);
            model.addAttribute("message","修改成功");
            return "blog/visitorUploadAvatar";
        } catch (Exception e) {
            model.addAttribute("message","修改失败");
            return "blog/visitorUploadAvatar";
        }
    }

    @RequestMapping("/login")
    public String login(Visitor visitor, Model model, HttpSession session) throws NoSuchAlgorithmException {
        Visitor getVisitor = null;
        if (visitor!=null){
            getVisitor = visitorService.getOne(new QueryWrapper<Visitor>().eq("visitorEmail", visitor.getVisitorEmail()));
        }else {
            model.addAttribute("errMessage","未获取到用户信息");
        }
        if(getVisitor!=null){
            if (!getVisitor.getPassword().equals(MD5Util.EncoderPwdByMd5(visitor.getPassword()))) {
                model.addAttribute("errMessage", "密码错误，请重新输入密码！");
            } else {
                model.addAttribute("okMessage", "登录成功！");
                session.setAttribute("getVisitor", getVisitor);
                return "redirect:/";
            }
        }else {
            model.addAttribute("errMessage","该用户不存在");
        }
        model.addAttribute("visitor", visitor); // 保存用户输入的数据
        return "blog/visitorLogin";
    }

    @RequestMapping("/register")
    public String register(Visitor visitor, @RequestParam String password2, Model model, RedirectAttributes redirectAttributes) throws NoSuchAlgorithmException {
        if (visitor==null){
            model.addAttribute("errMessage","未获取到用户");
            return "blog/visitorRegister";
        }else {
            if (!visitor.getPassword().equals(password2)){
                model.addAttribute("errMessage","两次输入密码的不相同，请重新输入密码！");
                model.addAttribute("visitorRegister", visitor); // 保持用户输入的数据
                model.addAttribute("password2",password2);
                return "blog/visitorRegister";
            }
            if (!EmailUtil.isValidEmail(visitor.getVisitorEmail())){
                model.addAttribute("errMessage", "邮箱格式错误，请重新输入邮箱！");
                model.addAttribute("visitorRegister", visitor); // 保持用户输入的数据
                model.addAttribute("password2",password2);
                return "blog/visitorRegister";
            }
            Visitor visitorEmail = visitorService.getOne(new QueryWrapper<Visitor>().eq("visitorEmail", visitor.getVisitorEmail()));
            if (visitorEmail!=null){
                model.addAttribute("errMessage", "该邮箱已注册！");
                model.addAttribute("visitorRegister", visitor); // 保持用户输入的数据
                model.addAttribute("password2",password2);
                return "blog/visitorRegister";
            }
            visitor.setVisitorAvatar("defaultAvatar.jpg");//设置默认头像
            visitor.setPassword(MD5Util.EncoderPwdByMd5(password2)); //密码加密
            visitorService.save(visitor); //保存实体
            redirectAttributes.addFlashAttribute("okMessage", "注册成功");
            return "redirect:/visitor/visitorLogin";
        }
    }

    /**
     * 添加评论
     */
    @RequestMapping("/comment")
    @ResponseBody
    public void comment(@RequestParam String comment,@RequestParam Integer articleId, Model model, HttpSession session) throws NoSuchAlgorithmException {
        Visitor visitor = (Visitor) session.getAttribute("getVisitor");//获取当前游客
        Comment newComment = new Comment();
        newComment.setMessage(comment);
        newComment.setVisitorId(visitor.getId());
        newComment.setReleaseDate(new Date());
        newComment.setArticleId(articleId);
        commentService.save(newComment);
    }

    /**
     * 退出登录
     * @param model
     * @param session
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping("/loginOut")
    @ResponseBody
    public void loginOut(Model model,HttpSession session) throws NoSuchAlgorithmException {
        session.removeAttribute("getVisitor");
        if (session.getAttribute("getVisitor") == null) {
            model.addAttribute("errMessage", "退出成功！");
        } else {
            model.addAttribute("errMessage", "退出失败！");
        }
    }



    @RequestMapping("/visitorLogin")
    public String visitorLogin(Model model) {
        return "blog/visitorLogin";
    }

    @RequestMapping("/visitorRegister")
    public String visitorRegister() {
        return "blog/visitorRegister";
    }

    @RequestMapping("/visitorUploadAvatar")
    public String uploadAvatar() {
        return "blog/visitorUploadAvatar";
    }

}
